<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form :inline="true" ref="searchForm" :model="searchObj" :rules="searchRules" label-width="80px">
        <el-form-item label="员工编号" prop="empNo">
          <el-input placeholder="请输入" v-model.trim="searchObj.empNo" @keyup.enter.native='doSearch()'>
          </el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="empName">
          <el-input placeholder="请输入" v-model.trim="searchObj.empName" @keyup.enter.native='doSearch()'>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNum">
          <el-input placeholder="请输入" v-model.trim="searchObj.phoneNum" @keyup.enter.native='doSearch()'>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch">搜索</el-button>
          <el-button type="primary" @click="doReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>


    <el-row>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-tree
            :props="treeProps"
            :load="loadNode"
            lazy
            :expand-on-click-node="false"
            @node-click="nodeClick"
            >
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <el-row class="mt-20 pl-10" type="flex" justify="start" :gutter="20">
          <el-button type="success" @click="showDialog('新增')">新增</el-button>
        </el-row>
        <el-table class="mt-20" :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="empNo" label="员工编号" width="80">
          </el-table-column>
          <el-table-column prop="empName" label="姓名" width="100">
          </el-table-column>
          <el-table-column prop="depName" label="部门">
          </el-table-column>
          <el-table-column prop="acctName" label="账号" width="120">
          </el-table-column>
          <el-table-column prop="roleName" label="角色">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
            <template slot-scope="scope">
              <span>{{new Date(scope.row.createTime).Format('yyyy-MM-dd hh:mm:ss')}}</span>
            </template>

          </el-table-column>
          <el-table-column prop="estateId" label="状态" width="80">
            <template slot-scope="scope">
              <span>{{enableAccountList.find(item=> item.key==scope.row.isEnableAccount).value}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="showDialog('编辑',scope.row.acctName)">编辑</el-button>
              <el-button type="text" size="small" @click="resetPasswordAsync(scope.row.acctName)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="mt-20" type="flex" justify="center">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizes"
            :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </el-row>
      </el-col>
    </el-row>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="dialogTitle=='新增'" label="部门">

          <el-cascader
            :show-all-levels="false"
            :options="departmentList"
            @active-item-change="handleItemChange"
            :props="props"
            v-model="departmentId" placeholder="请选择"
          ></el-cascader>

        </el-form-item>
        <el-form-item v-if="dialogTitle=='新增'" label="员工" prop="empId">
          <el-select v-model="form.empId" placeholder="请选择" :disabled="departmentId.length==0" @change="empChange">
            <el-option v-for="item in empList" :key="item.empId" :label="item.empName" :value="item.empId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogTitle=='新增'" label="员工编号">
          <el-input v-model="form.empNo" disabled></el-input>
        </el-form-item>
        <el-form-item v-if="dialogTitle=='新增'" label="员工姓名">
          <el-input v-model="form.empName" disabled></el-input>
        </el-form-item>
        <el-form-item v-if="dialogTitle=='新增'" label="联系方式">
          <el-input v-model="form.phoneNum" disabled></el-input>
        </el-form-item>
        <el-form-item v-if="dialogTitle=='编辑'" label="账号">
          <el-input v-model="acctName" disabled></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="estateId">
          <el-select v-model="form.isEnableAccount" placeholder="请选择">
            <el-option v-for="item in enableAccountList" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEdit">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {
    findAllAccount,findAccountParentDept,findAccountChildrenDept,findEmpByDept,findRoles,findAccount,
    addAccount,updateAccount,resetPassword
  } from "@/api/departPersonManage/personManagement";
  import {
    departManagementTreeData,departmentList
  } from "@/constants/mockDatas";
  import {
    enableAccountList
  } from "@/constants/code";
  import {
    deleteConfirm
  } from "@/utils/deleteConfirm";
  import {
    requireInput,requireInputWithMaxLengthN,phoneNumInputN
  } from "@/utils/validateForm";
  import "@/utils/toDate";

  export default {
    data() {

      return {
        inpDisabled: true,
        treeProps: {
          label: 'departmentName',
          children: 'zones',
          isLeaf: 'leaf'
        },
        acctName: '1345',
        searchObj: {
          empNo: "",
          phoneNum: "",
          empName: "",
        },
        searchRules: {
          empNo: requireInputWithMaxLengthN(),
          empName: requireInputWithMaxLengthN(),
          phoneNum: [...phoneNumInputN,...requireInputWithMaxLengthN()],
        },

        departmentId: [],
        list: [],
        listLoading: false,
        currentPage: 1,
        total: 0,
        pageSize: 5,
        pageSizes: [5, 10],
        btnDisabled: true,
        multipleSelection: [],
        dialogVisible: false,
        dialogTitle: "新增",
        form: {
          empId: '',
          empNo: '',
          empName: '',
          phoneNum: '',
          estateId: '',
          roleId: '',
          isEnableAccount: '',
        },
        rules: {

          isEnableAccount: requireInput("请选择",'change'),
          isEnableAccount: requireInput("请选择",'change'),
          roleId: requireInput("请选择",'change')
        },
        departmentList,
        enableAccountList,
        roleList: [],
        departmentList: [],
        empList: [],
        props: {
          label: 'departmentName',
          value: 'departmentId',
          children: 'zones'
        },
      };
    },
    watch: {
      // departmentId() {
      //   this.findEmpByDeptAsync();
      // }
    },

    created() {
      this.findRolesAsync();
      this.findAccountParentDeptAsync();
      this.findAllAccountAsync();
    },
    methods: {
      doSearch() {

        this.$refs.searchForm.validate(vaild=> {
          if(vaild) {
            this.findAllAccountAsync();
          }
        })
      },

      doReset() {
        this.$refs.searchForm.resetFields(); //对整个表单进行重置
        this.findAllAccountAsync();
      },

      nodeClick(data) {
        this.departmentId = data.departmentId;
        this.findAllAccountAsync();
      },

      showDialog(type, acctName = false) {
        this.dialogTitle = type;
        if (acctName) {
          this.findAccountAsync(acctName);
        }else {
          this.form = {
            empId: '',
            empNo: '',
            empName: '',
            phoneNum: '',
            estateId: '',
            roleId: '',
            isEnableAccount: '',
          }
          console.log(this.form);
        }
        this.dialogVisible = true;
      },

      addOrEdit() {
        if (this.dialogTitle == "新增") {
          this.addAccountAsync()
        } else {
          this.updateAccountAsync()
        }


      },

      handleClose() {
        this.dialogVisible = false;
        this.form = {
          empId: '',
          empNo: '',
          empName: '',
          phoneNum: '',
          estateId: '',
          roleId: '',
          isEnableAccount: '',
        };
      },



      handleSizeChange(val) {
        this.pageSize = val;
        this.findAllAccountAsync();
      },

      handleCurrentChange(val) {
        this.currentPage = val;
        this.findAllAccountAsync();
      },


      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.btnDisabled = this.multipleSelection.length < 1;
      },

      empChange(val) {
        let {empNo,empName,empPhone} = this.empList.find(item=> item.empId==val);
        this.form.empNo = empNo;
        this.form.empName = empName;
        this.form.phoneNum = empPhone;
      },

      async findAllAccountAsync() {
        let departmentIdObj = typeof this.departmentId=='string' ? {departmentId:this.departmentId} : {departmentId:this.departmentId.join()}
        let {code,data,msg} = await findAllAccount({
          ...departmentIdObj,
          ...this.searchObj},{
          page: this.page,
          pageSize: this.pageSize
        });
        if(code=='00000') {
          this.list = data.rows;
          this.total = data.total;
        }
      },

      async handleItemChange(val) {
        let _departmentId = val[val.length-1];
        let {code,data,msg} = await findAccountChildrenDept({
          departmentId: _departmentId
        });
        if(code=='00000') {
          let _data = data.map(item=> {
            if(item.hasChild) {
              item.zones = [];
            }
            return item
          });

          let recursion = (list)=> {
            list.forEach((item,index,arr) => {
              if(item.departmentId == _departmentId) {
                if(arr[index].hasOwnProperty('zones')) {
                  arr[index].zones = _data;
                }
              }else{
                if(item.hasOwnProperty('zones')) {
                  recursion(item.zones);
                }
              }
            })
          }
          recursion(this.departmentList)

        }
      },


      async findEmpByDeptAsync() {
        let {code,data,msg} = await findEmpByDept({
          departmentId: this.departmentId[this.departmentId.length-1]
        });
        if(code=='00000') {
          this.empList = data;
        }
      },

      async loadNode(node, resolve) {

        if (node.level === 0) {
          let {code,data,msg} = await findAccountParentDept();
          if(code == '00000') {
            this.treeProps = {
              label: 'departmentName',
              children: 'zones',
              isLeaf: 'leaf'
            };
            return resolve(data);
          }

        }

        let {code,data,msg} = await findAccountChildrenDept({
          departmentId: node.data.departmentId
        });
        resolve(data);

      },

      async findAccountParentDeptAsync() {
        let {code,data,msg} = await findAccountParentDept();
        if(code==='00000') {
          this.departmentList = data.map(item=> {
            if(item.hasChild) {
              item.zones = [];
            }
            return item;
          });
        }
      },

      async findRolesAsync() {
        let {code,data,msg} = await findRoles();
        if(code=='00000') {
          this.roleList = data;
        }
      },

      async findAccountAsync(acctName) {
        let {code,data,msg} = await findAccount({
          acctName
        });
        if(code=='00000') {
          this.acctName = data.acctName;
          this.form.roleId = data.employeeRole.roleId;
          console.log(data.employeeRole.roleId);
          this.form.isEnableAccount = data.isEnableAccount;
        }
      },

      async addAccountAsync() {
        let {code,data,msg} = await addAccount(this.form);
        if(code=='00000') {

          if(data.flag) {
            let pwd = this.form.phoneNum.substr( this.form.phoneNum.length-6)
            this.message({
              type: 'success',
              message: `密码为${pwd}`
            })
          }

          this.findAllAccountAsync();
          this.dialogVisible = false;
        }
      },

      async updateAccountAsync() {

        let {code,data,msg} = await updateAccount({
          acctName: this.acctName,
          ...this.form
        });
        if(code=='00000') {
          this.findAllAccountAsync();
          this.dialogVisible = false;
        }
      },

      async resetPasswordAsync(acctName) {
        let {code,dat,msg} = await resetPassword({
          acctName
        });
        if(code=='00000') {
          let pwd = acctName.substr(acctName.length-6)
          this.$message({
            type: 'success',
            message: `重置成功，密码为${pwd}`
          })
          this.findAllAccountAsync();
        }
      }


    }
  };

</script>
